import { defineStore } from 'pinia'
import { login as apiLogin, updatePassword as apiUpdatePassword } from '../api'

export const useUserStore = defineStore('user', {
  state: () => ({
    username: localStorage.getItem('username') || '',
    role: localStorage.getItem('role') || '',
    isLoggedIn: !!localStorage.getItem('token') || false,
    token: localStorage.getItem('token') || ''
  }),
  actions: {
    async login(username, password, role) {
      try {
        const response = await apiLogin(username, password, role.toUpperCase())
        if (response.data.success) {
          const { username: loggedInUsername, role: loggedInRole, token } = response.data.data
          this.username = loggedInUsername
          this.role = loggedInRole
          this.isLoggedIn = true
          this.token = token
          localStorage.setItem('username', loggedInUsername)
          localStorage.setItem('role', loggedInRole)
          localStorage.setItem('token', token)
          return { success: true, message: '登录成功' }
        } else {
          throw new Error(response.data.message || '登录失败')
        }
      } catch (error) {
        console.error('Login error:', error.response ? error.response.data : error.message)
        throw new Error(error.response ? error.response.data.message : '网络或服务器错误')
      }
    },
    logout() {
      this.username = ''
      this.role = ''
      this.isLoggedIn = false
      this.token = ''
      localStorage.removeItem('username')
      localStorage.removeItem('role')
      localStorage.removeItem('token')
    },
    async updatePassword(username, newPassword) {
      try {
        const response = await apiUpdatePassword(username, newPassword)
        if (response.data.success) {
          return { success: true, message: response.data.message }
        } else {
          throw new Error(response.data.message || '密码更新失败')
        }
      } catch (error) {
        console.error('Update password error:', error.response ? error.response.data : error.message)
        throw new Error(error.response ? error.response.data.message : '网络或服务器错误')
      }
    }
  }
})